package com.hzz.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 跨域是当前域名的请求下其他域名的资源才会发生，这里是跳转页面
 */
@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String s = stringRedisTemplate.opsForValue().get(token);
        return s;
    }

    //登录页面    参数url判断是那个网站登录的
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url,
         Model model, @CookieValue(value = "sso_token",required = false) String sso_token){
        if(!StringUtils.isEmpty(sso_token)){
            //说明之前有人登录过
            return "redirect:"+url+"?token="+sso_token;
        }
        model.addAttribute("url1", url);
        System.out.println(url);
        return "login";
    }

    //登录验证
    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String url,
                          HttpServletResponse response){
        //登录成功跳转，跳回到之前的页面
        if (!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password)){
            //登录成功

            //把登录成功的用户保存起来
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid,username);
            //cookie保存到的是ssoserve这个服务
            //浏览器以后访问这个域名都带上这个cookie  (当前浏览器)
            //client1登录成功 sssoserve保留一个cookie client2再登录请求就会带来ssoserve中的cookie
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:"+url+"?token="+uuid;
        }
        return "login";
    }
}
